﻿/*
 * Author:xmfdsh 11届网络部--邓世豪
 * DataTime：2014-6-9
 * Copyright © 2014 大学生勤工助学服务队 Powered by xmfdsh & 四小狼工作室.
 * 版权所有，违者必究
 */
using Common.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.SessionState;

namespace QGZX.Helper
{
    /// <summary>
    /// 网站操作上下文
    /// </summary>
    public class OperateContext
    {

        //---------------------定义常量
        const string Admin_CookiePath = "/admin/";
        const string Admin_InfoKey = "ainfo";
        const string Admin_PermissionKey = "apermission";
        const string Admin_LogicSessionKey = "BLLSession";
        const string Admin_TreeString = "aTreeString";

        const string User_CookiePath = "/user/";
        const string User_InfoKey = "uinfo";
        const string User_PermissionKey = "upermission";

        //定义静态变量 标识用户类型,进行分类处理
        public static int user_status = 0 ;

        /// <summary>
        /// 业务仓储
        /// </summary>
        public IBLL.IBLLSession BLLSession;

        //---------------------定义上下文属性
        #region 实例构造函数 初始化业务仓储 + OperateContext()
        public OperateContext()
        {
            BLLSession = DI.SpringHelper.GetObject<IBLL.IBLLSession>("BLLSession");
        } 
        #endregion

        #region Http上下文 以及相关属性 
        /// <summary>
        /// Http上下文
        /// </summary>
        HttpContext ContextHttp
        {
            get
            {
                return HttpContext.Current;
            }
        }

        HttpResponse Response
        {
            get
            {
                return ContextHttp.Response;
            }
        }
        HttpRequest Request
        {
            get
            {
                return ContextHttp.Request;
            }
        }
        HttpSessionState Session
        {
            get
            {
                return ContextHttp.Session;
            }
        }
        #endregion

        #region 获取当前操作上下文(存在线程中，提高效率) + OperateContext Current
        // <summary>
        /// 获取当前操作上下文(存在线程中，提高效率)
        /// </summary>
        public static OperateContext Current
        {
            get
            {
                OperateContext o = CallContext.GetData(typeof(OperateContext).Name) as OperateContext;
                if (o == null)
                {
                    o = new OperateContext();
                    CallContext.SetData(typeof(OperateContext).Name, o);
                }
                return o;
            }
        } 
	    #endregion

        #region 管理员权限 + List<MODEL.qgzx_permission> AdminPermission
        /// <summary>
        /// 用户权限
        /// </summary>
        public List<MODEL.qgzx_permission> AdminPermission
        {
            get
            {
                return Session[Admin_PermissionKey] as List<MODEL.qgzx_permission>;
            }
            set
            {
                Session[Admin_PermissionKey] = value;
            }
        } 
        #endregion

        #region 用户权限 + List<MODEL.qgzx_permission> UserPermission
        /// <summary>
        /// 用户权限
        /// </summary>
        public List<MODEL.qgzx_permission> UserPermission
        {
            get
            {
                return Session[User_PermissionKey] as List<MODEL.qgzx_permission>;
            }
            set
            {
                Session[User_PermissionKey] = value;
            }
        }
        #endregion

        #region 当前登录管理员对象 +MODEL.qgzx_admin Admin
        /// <summary>
        /// 当前登录用户对象
        /// </summary>
        public MODEL.qgzx_admin Admin
        {
            get
            {
                return Session[Admin_InfoKey] as MODEL.qgzx_admin;
            }
            set
            {
                Session[Admin_InfoKey] = value;
            }
        }
        #endregion

        #region 当前登录学生对象 +MODEL.qgzx_student Student
        /// <summary>
        /// 当前登录学生对象
        /// </summary>
        public MODEL.qgzx_student_information Student
        {
            get
            {
                return Session[User_InfoKey] as MODEL.qgzx_student_information;
            }
            set
            {
                Session[User_InfoKey] = value;
            }
        }
        #endregion

        #region 当前登录单位对象 +MODEL.qgzx_company company
        /// <summary>
        /// 当前登录单位对象
        /// </summary>
        public MODEL.qgzx_company Company
        {
            get
            {
                return Session[User_InfoKey] as MODEL.qgzx_company;
            }
            set
            {
                Session[User_InfoKey] = value;
            }
        }
        #endregion

        #region 当前登录老师对象 +MODEL.qgzx_teacher Teacher
        /// <summary>
        /// 当前登录老师对象
        /// </summary>
        public MODEL.qgzx_teacher Teacher
        {
            get
            {
                return Session[User_InfoKey] as MODEL.qgzx_teacher;
            }
            set
            {
                Session[User_InfoKey] = value;
            }
        }
        #endregion

        //---------------------管理员登陆注销等系统操作

        #region 管理员 登陆业务 +  ActionResult Login()
        public bool LoginAdmin(MODEL.ViewModel.LoginAdmin adminPara)
        {
            MODEL.qgzx_admin admin = BLLSession.Iqgzx_adminBLL.Login(adminPara.LoginName, adminPara.Password);
            if (admin != null)
            {
                //保存用户数据(cookie)
                if (adminPara.IsAlways)
                {
                    //加密 用户id
                    string AdminCookie = Common.SecurityHelper.EncryptAdminInfo(admin.Id.ToString());
                    //创建coodie
                    HttpCookie cookie = new HttpCookie(Admin_InfoKey, AdminCookie);
                    cookie.Expires = DateTime.Now.AddDays(1);
                    cookie.Path = Admin_CookiePath;
                    Response.Cookies.Add(cookie);
                }
                //保存用户数据 session
                Admin = admin;
                //保存权限
                AdminPermission = GetAdminPermission(admin.Id);
                return true;
            }
            return false;
        } 
        #endregion

        #region 判断当前管理员是否登陆 + bool IsLogin()
        /// <summary>
        /// 判断当前管理员是否登陆
        /// </summary>
        /// <returns></returns>
        public bool IsLogin()
        {
            //1.验证用户是否登陆(Session && Cookie)
            if (Session[Admin_InfoKey] == null)
            {
                if (Request.Cookies[Admin_InfoKey] == null)
                {
                    return false;
                }
                else//如果有cookie则从cookie中获取用户id并查询相关数据存入 Session
                {
                    string strAdminInfo = Request.Cookies[Admin_InfoKey].Value;
                    //可能为空 bug
                    strAdminInfo = Common.SecurityHelper.DecryptAdminInfo(strAdminInfo);
                    int adminId = int.Parse(strAdminInfo);
                    MODEL.qgzx_admin admin = BLLSession.Iqgzx_adminBLL.GetListBy(u => u.Id == adminId).First();
                    Admin = admin;
                    AdminPermission = GetAdminPermission(admin.Id);
                }
            }
            return true;
        } 
        #endregion

        #region 判断当前管理员是否有访问当前页面权限 + bool HasPermission
        /// <summary>
        /// 判断当前管理员是否有访问当前页面权限
        /// </summary>
        /// <param name="areaName"></param>
        /// <param name="actionName"></param>
        /// <param name="controllerName"></param>
        /// <returns></returns>
        public bool HasPermission(string areaName, string controllerName, string actionName)
        {
            var s = from per in AdminPermission
                    where
                        string.Equals(per.PAreaName, areaName, StringComparison.CurrentCultureIgnoreCase) &&
                        string.Equals(per.PControllerName, controllerName, StringComparison.CurrentCultureIgnoreCase) &&
                        string.Equals(per.PActionName, actionName, StringComparison.CurrentCultureIgnoreCase)
                    select per;
            return s.Count() > 0;
        } 
        #endregion

        #region  获取当前登陆管理员的权限树Json字符串 +string UsrTreeJsonStr
        /// <summary>
        /// 获取当前登陆管理员的权限树Json字符串
        /// </summary>
        public string UsrTreeJsonStr
        {
            get
            {
                if (Session[Admin_TreeString] == null)
                {
                    //将 登陆用户的 权限集合 转成 树节点 集合（其中 IsShow = false的不要生成到树节点集合中）
                    List<MODEL.EasyUIModel.TreeNode> listTree = MODEL.qgzx_permission.ToTreeNodes(AdminPermission.Where(p => p.IsShow == true).ToList());
                    Session[Admin_TreeString] = Common.DataHelper.Obj2Json(listTree);
                }  
                return Session[Admin_TreeString].ToString();
            }
        }
        #endregion

        #region 根据管理员id查询用户权限
        /// <summary>
        /// 根据管理员id查询用户权限
        /// </summary>
        /// <param name="adminId"></param>
        public List<MODEL.qgzx_permission> GetAdminPermission(int adminId)
        {
            //根据用户id查询用户实体模型
            MODEL.qgzx_admin listAdmin = Current.BLLSession.Iqgzx_adminBLL.GetListBy(p => p.Id == adminId).First();
            //查询 用户相应部门表中的 PermissionId 字符串（格式为：1|2|3）
            string listPermissionStr = Current.BLLSession.Iqgzx_departmentBLL.GetListBy(u => u.Id == listAdmin.DepartmentId).ToList().First().PermissionId.ToString();
            //分离PermissionId字符串  并转成List<int>
            List<int> PermissionInt = listPermissionStr.Split(new string[1] { "|" }, StringSplitOptions.RemoveEmptyEntries).Select(f => int.Parse(f)).ToList();
            //查找qgzx_permission 表中包含 PermissinoInt的行
            List<MODEL.qgzx_permission> listPermission = Current.BLLSession.Iqgzx_permissionBLL.GetListBy(m => PermissionInt.Contains(m.PId)).ToList();
            return listPermission;
        }
        #endregion

        #region 根据部门id获取权限  生成权限树 + GetPermissionByDeparId(int DepartmentId)
        /// <summary>
        /// 根据部门id获取权限  生成权限树
        /// </summary>
        /// <param name="adminId"></param>
        /// <returns></returns>
        public List<MODEL.qgzx_permission> GetPermissionByDeparId(int DepartmentId)
        {

            //查询 用户相应部门表中的 PermissionId 字符串（格式为：1|2|3）
            string listPermissionStr = Current.BLLSession.Iqgzx_departmentBLL.GetListBy(u => u.Id == DepartmentId).ToList().First().PermissionId.ToString();
            //分离PermissionId字符串  并转成List<int>
            List<int> PermissionInt = listPermissionStr.Split(new string[1] { "|" }, StringSplitOptions.RemoveEmptyEntries).Select(f => int.Parse(f)).ToList();
            //查找qgzx_permission 表中包含 PermissinoInt的行
            List<MODEL.qgzx_permission> listPermission = Current.BLLSession.Iqgzx_permissionBLL.GetListBy(m => PermissionInt.Contains(m.PId)).ToList();
            return listPermission;
        }
        #endregion

        //--------------------系统用户登录注销等系统操作

        #region 系统用户登陆业务 + UserLogin(MODEL.ViewModel.LoginUser userPara)
        public bool UserLogin(MODEL.ViewModel.LoginUser userPara)
        {
            if (userPara.Status == 1)//用户为学生
            {
                MODEL.qgzx_student_information student = BLLSession.Iqgzx_student_informationBLL.Login(userPara.LoginName, userPara.Password);
                if ( student != null)
                {
                    //修改为学生登录，默认0。
                    user_status = 1;
                    //保存用户数据(cookie)
                    if (userPara.IsAlways)
                    {
                        //加密 用户id
                        string UserCookie = Common.SecurityHelper.EncryptAdminInfo(student.StudentId.ToString());
                        //创建coodie
                        HttpCookie cookie = new HttpCookie(User_InfoKey, UserCookie);
                        cookie.Expires = DateTime.Now.AddDays(1);
                        cookie.Path = User_CookiePath;
                        Response.Cookies.Add(cookie);
                    }
                    //保存用户数据 session
                    Student = student;
                    //从数据库获取学生权限，绑定id为4
                    UserPermission = GetPermissionByDeparId(4);
                    return true;
                }
            }

            if (userPara.Status == 2)//用户为老师
            {
                MODEL.qgzx_teacher teacher = BLLSession.Iqgzx_teacherBLL.Login(userPara.LoginName, userPara.Password);
                if (teacher != null)
                {
                    //修改为老师登录，默认10。
                    user_status = 2;
                    //保存用户数据(cookie)
                    if (userPara.IsAlways)
                    {
                        //加密 用户id
                        string CompanyCookie = Common.SecurityHelper.EncryptAdminInfo(teacher.Id.ToString());
                        //创建coodie
                        HttpCookie cookie = new HttpCookie(User_InfoKey, CompanyCookie);
                        cookie.Expires = DateTime.Now.AddDays(7);
                        cookie.Path = User_CookiePath;
                        Response.Cookies.Add(cookie);
                    }
                    //保存用户数据 session
                    Teacher = teacher;
                    //从数据库获取老师权限，绑定id为5
                    UserPermission = GetPermissionByDeparId(5);
                    return true;
                }
            }

            if (userPara.Status == 3)//用户为单位
            {
                MODEL.qgzx_company company = BLLSession.Iqgzx_companyBLL.Login(userPara.LoginName, userPara.Password);
                if ( company != null)
                {
                    //修改为单位登录，默认0。
                    user_status = 3;
                    //保存用户数据(cookie)
                    if (userPara.IsAlways)
                    {
                        //加密 用户id
                        string CompanyCookie = Common.SecurityHelper.EncryptAdminInfo(company.CompanyId.ToString());
                        //创建coodie
                        HttpCookie cookie = new HttpCookie(User_InfoKey, CompanyCookie);
                        cookie.Expires = DateTime.Now.AddDays(7);
                        cookie.Path = User_CookiePath;
                        Response.Cookies.Add(cookie);
                    }
                    //保存用户数据 session
                    Company = company;
                    //从数据库获取单位权限，绑定id为2
                    UserPermission = GetPermissionByDeparId(2);
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region 判断当前用户是否登陆 + int IsLoginUser()
        /// <summary>
        /// 判断当前用户是否登陆
        /// </summary>
        /// <returns></returns>
        public bool IsLoginUser()
        {
            //1.验证用户是否登陆(Session && Cookie)
            if (Session[User_InfoKey] == null)
            {
                if (Request.Cookies[User_InfoKey] == null)
                {
                    return false;
                }
                else//如果有cookie则从cookie中获取用户id并查询相关数据存入 Session
                {
                    string strUserInfo = Request.Cookies[User_InfoKey].Value;
                    //可能为空 bug
                    strUserInfo = Common.SecurityHelper.DecryptAdminInfo(strUserInfo);
                    int userId = int.Parse(strUserInfo);
                    
                    if (user_status == 1)
                    {
                        MODEL.qgzx_student_information student = BLLSession.Iqgzx_student_informationBLL.GetListBy(u => u.StudentId == userId).First();
                        Student = student;
                    }
                 
                    if(user_status == 2)
                    {
                        MODEL.qgzx_teacher teacher = BLLSession.Iqgzx_teacherBLL.GetListBy(t => t.Id == userId).First();
                        Teacher = teacher;
                    }

                    if (user_status == 3)
                    {
                        MODEL.qgzx_company company = BLLSession.Iqgzx_companyBLL.GetListBy(c => c.CompanyId == userId).First();
                        Company = company;
                    }
                    return true;
                }
            }
            return true;
        }
        #endregion

        #region 判断当前用户是否有访问当前页面权限 + bool HasUserPermission
        /// <summary>
        /// 判断当前用户是否有访问当前页面权限
        /// </summary>
        /// <param name="areaName"></param>
        /// <param name="actionName"></param>
        /// <param name="controllerName"></param>
        /// <returns></returns>
        public bool HasUserPermission(string areaName, string controllerName, string actionName)
        {
            var s = from per in UserPermission
                    where
                        string.Equals(per.PAreaName, areaName, StringComparison.CurrentCultureIgnoreCase) &&
                        string.Equals(per.PControllerName, controllerName, StringComparison.CurrentCultureIgnoreCase) &&
                        string.Equals(per.PActionName, actionName, StringComparison.CurrentCultureIgnoreCase)
                    select per;
            return s.Count() > 0;
        }
        #endregion


        //-------------------------------------------------------//公共操作方法
        #region 生成json格式返回值 + ActionResult RedirectAjax
        /// <summary>
        /// 生成json格式返回值
        /// </summary>
        /// <param name="statu"></param>
        /// <param name="msg"></param>
        /// <param name="data"></param>
        /// <param name="backurl"></param>
        /// <returns></returns>
        public ActionResult RedirectAjax(string statu, string msg, object data, string backurl)
        {
            MODEL.FormatModel.AjaxMsgModel ajaxM = new MODEL.FormatModel.AjaxMsgModel()
            {
                Statu = statu,
                Msg = msg,
                Data = data,
                BackUrl = backurl
            };
            JsonResult res = new JsonResult();
            res.Data = ajaxM;
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return res;
        } 
        #endregion

        #region 当前重定向方法 1.如果是ajax请求，返回json字符串 2。如果普通请求，返回重定向命令
        /// <summary>
        /// 当前重定向方法 1.如果是ajax请求，返回json字符串 2。如果普通请求，返回重定向命令
        /// </summary>
        /// <returns></returns>
        public ActionResult Redirect(string url, ActionDescriptor action)
        {
            //如果 ajax请求没有权限 返回json消息
            if (action.IsDefined(typeof(AjaxRequestAttribute), false)
                || action.ControllerDescriptor.IsDefined(typeof(AjaxRequestAttribute), false))
            {
                return RedirectAjax("nologin", "您还没有登陆或没有权限", null, url);
            }
            else//如果超链接或表单 没权限 ，返回重定向
            {
                return new RedirectResult(url);
            }
        }
        #endregion

        
        
        
        
        /// <summary>
        /// 公共方法，申请岗位 后对applyStudent字符串进行添加
        /// </summary>
        /// <param name="positinId">要申请的岗位id</param>
        /// <returns>这里规定返回格式 1.岗位已经被删除2.没有登陆3.已经申请过了，4.申请成功</returns>
        //public int ConnectApplyStudent(int positinId)
        //{
            
        //    MODEL.qgzx_position model = OperateContext.Current.BLLSession.Iqgzx_positionBLL.GetListBy(x => x.PositionId == positinId).FirstOrDefault();
        //    //查询得到批准参与工作的学生
        //    string ApplyStudent = model.ApplyStudentsId;
        //    if (model.IsDel == 1)
        //        return 1;
        //    int id;
        //    if(User==null)
        //    {
        //        return 2;
        //    }
        //    else
        //    {
        //        id = User.StudentId;
        //    }
        //    List<int> ApplyStudentList = ApplyStudent.Split(new string[1] { "|" }, StringSplitOptions.RemoveEmptyEntries).Select(f => int.Parse(f)).ToList();
        //    //查看是否包含该学生
        //    if (ApplyStudentList.Contains(id))
        //    {
        //        return 3;
        //    }
        //    else
        //    {
        //        ApplyStudentList.Add(id);
        //    }
        //    string list = "";
        //    foreach (int i in ApplyStudentList)
        //    {
        //        list += "|";
        //        list += i;
        //    }
        //    model.ApplyStudentsId = list;

        //    OperateContext.Current.BLLSession.Iqgzx_positionBLL.ModifyBy(model, x => x.PositionId == model.PositionId, "ApplyStudentsId");
        //    return 4;
        //}
       
    }
}
